package com.stox.core.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import com.stox.core.dao.mapper.BarRowMapper;
import com.stox.core.manager.ScripManager;
import com.stox.core.model.Bar;
import com.stox.core.model.IBar;
import com.stox.core.model.exception.StoxException;
import com.stox.design.DatabaseConfigurer;

public class BarDao1 extends AbstractDao implements DatabaseConfigurer{

	private BarRowMapper barRowMapper;
	private ScripManager scripManager;

	
	@Override
	public int getOrder() {
		return 0;
	}
	
	@Override
	public Object invoke(List<String> payload) {
		if(!payload.contains("BAR")){
			try {
				getConnection().createStatement().execute(BarRowMapper.getCreateSql(""));
				getConnection().createStatement().execute(BarRowMapper.getCreateIndexSql(""));
			} catch (SQLException e) {
				throw new StoxException(e);
			}
		}
		return null;
	}
	
	public List<Bar> get(String scripCode) throws SQLException{
		String sql = BarRowMapper.getSelectSql(scripCode)+" order by bardate desc";
		PreparedStatement ps = getConnection().prepareStatement(sql);
		System.out.println(sql);
		return barRowMapper.map(ps.executeQuery());
	}
	
	public List<Bar> get(String scripCode, int count) throws SQLException{
		String sql = BarRowMapper.getSelectSql(scripCode)+" where code = ? order by bardate desc";
		PreparedStatement ps = getConnection().prepareStatement(sql);
		ps.setInt(1, count);
		ps.setString(2, scripCode);
		return barRowMapper.map(ps.executeQuery());
	}
	
	public void persist(List<Bar> bars) throws SQLException{
		if(bars != null && !bars.isEmpty()){
			for(IBar bar : bars){
				if(!scripManager.exists(bar.getScrip().getCode())){
					scripManager.persist(bar.getScrip());
				}
			}
			
			for(Bar bar : bars){
				PreparedStatement ps = getConnection().prepareStatement(
						BarRowMapper.getInsertSql(bar.getScripCode()));
				barRowMapper.map(ps, bar);
				ps.execute();
			}
			commit();
		}
	}

	public BarRowMapper getBarRowMapper() {
		return barRowMapper;
	}

	public void setBarRowMapper(BarRowMapper barRowMapper) {
		this.barRowMapper = barRowMapper;
	}

	public ScripManager getScripManager() {
		return scripManager;
	}

	public void setScripManager(ScripManager scripManager) {
		this.scripManager = scripManager;
	}
	
}
